package com.springboot.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理类
 */
@Slf4j
@ResponseBody
@ControllerAdvice(annotations = {RestController.class})//拦截带有RestController注解的类
public class GlobaExceptionHandle {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class) //捕获SQLIntegrityConstraintViolationException异常
    public R<String> ExceptionHandle(SQLIntegrityConstraintViolationException ex) {//异常处理方法
       log.info(ex.getMessage());//打印异常信息
        if(ex.getMessage().contains("Duplicate entry")){//判断异常信息是否包含“Duplicate entry”
            String[] split=ex.getMessage().split(" ");//分割异常信息
              String msg=split[2]+"用户已经存在";
              return  R.error(msg);
        }
        return R.error("未知异常");//返回错误信息
    }
    @ExceptionHandler( CustomException.class) //捕获CustomException异常
    public R<String> ExceptionHandle(CustomException ex) {//异常处理方法
         log.info(ex.getMessage());//打印异常信息
        return R.error(ex.getMessage());//返回错误信息
    }
}
